import { reqGetUserCode, reqGetUserRejister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
//引入token 外部调用
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/util/token-util'

const actions = {
    //验证码请求
    async getUserCode({ commit, dispatch, state, getters }, phone) {
        let result = await reqGetUserCode(phone)
        if (result.code === 200) {
            commit('USERCODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('获取验证码失败'))
        }
    },
    // 注册按钮
    async getUserRejster({ commit, dispatch, state, getters }, data) {
        let result = await reqGetUserRejister(data)
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(result.message)
        }
    },
    // 登录*********
    async getUserLogin({ commit, dispatch, state, getters }, data) {
        let result = await reqUserLogin(data)
        if (result.code === 200) {
            commit('USERLOGIN', result.data.token)
            // 获取到用户token,立马进行本地存储
            SET_TOKEN(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(result.message)
        }
    },
    // 获取用户信息校验token
    async getUserInfo({ commit, dispatch, state, getters }) {
        let result = await reqUserInfo()
        if (result.code === 200) {
            commit('USERINFO', result.data.nickName)
            return 'ok'
        } else {
            return Promise.reject('faile')
        }
    },
    // 退出登录
    async getLogout({ commit, dispatch, state, getters }) {
        let result = await reqLogout();
        if (result.code === 200) {
            commit('LOGOUT')
            return 'ok'
        } else {
            return Promise.reject('faile')
        }
    }

}
const state = {
    code: '',
    // 获取本地存储的token,刷新就不会出现bug
    token: GET_TOKEN(),
    nickName: ''
}
const getters = {}
const mutations = {
    USERCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    USERINFO(state, nickName) {
        state.nickName = nickName
    },
    LOGOUT(state) {
        state.token = ''
        state.nickName = ''
        // 移除token
        REMOVE_TOKEN()
    }
}

export default {
    actions,
    state,
    getters,
    mutations
}